function varargout = TLBusportDlg(action,varargin)

% TL_BUSPORT_DLG manages the user interface of TargetLink busport block
%
% SYNTAX dlgInfo = TLBusportDlg('GetDlgInfo');
%   gets dialog info of TargetLink Busport block
%
%   INPUT ARGUMENTS
%   -/-
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = ...
%           TLBusportDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLBusportDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLBusportDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLBusportDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLBusportDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Hints: FcnCreateTreeview uses nested function and must be closed with an 'end'.
%        Therefore all other functions must be closed with an 'end', too.
%        It is not allowed to use both conventions in the same file.
%
% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLBusportDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.72 $
% $Date: 2011/10/19 10:47:10MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


% push warning state and suppress warning messages regarding java callback functions
if get_param(0, 'version') >= 7.6
    bRestoreWarnings = true;
    tl_handle_warning_state('push');
    tl_handle_warning_state('set','MsgId', 'MATLAB:hg:JavaSetHGProperty', 'State', 'off');
else
    bRestoreWarnings = false;
end

% branch dependend on action
switch action,
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        % special solution, because businport and busoutport uses same dlg-function
        titleName = strrep(get_param(hBlock, 'MaskType'), 'TL_', '');
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        % return structure holding the names of tabs
        dlgInfo.pageNames = { ...
            'Output' ...
            'Logging & Autoscaling' ...
            'RTOS' ...
            'AUTOSAR' ...
            'Documentation'};
        % icon of switch for dual edit of output and AUTOSAR data
        dlgInfo.bDualEdit = 1;
        % get block data with codegen mode 'AUTOSAR' to have blockspecific AUTOSAR data in effecivescaling
        [tlData, extdata] = tl_get_effectivedata(hBlock);
        % set defaultPageNum to AUTOSAR page if AUTOSAR is enabled
        if extdata.bAutosarMode
            dlgInfo.defaultPageNum = 4;
        else
            dlgInfo.defaultPageNum = 1;
        end
        % initialize extended data
        dlgInfo.extdata.codegenmode = extdata.codegenmode;
        dlgInfo.extdata.bAutosarMode = extdata.bAutosarMode;
        dlgInfo.extdata.bIsEditMode = false;
        varargout{1} = dlgInfo;
        varargout{2} = tlData;
        
    case 'CtrlPositions',
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        buscorr = commonGeom.treeviewWidth + commonGeom.frameDelta + 2*commonGeom.frameSideEdgeBuffer;
        % bCodeComment = varargin{5}; (= isfield(dlgdata.data,'comment'))
        % bus port dialog may be opened with port data and bCodeComment = 1
        switch pageName,
            case 'Output',
                % additional input neccessary for difference between inport and outport
                excludedCtrls = varargin{6};
                [sheetDims, ctrlPos] = FcnCalcOutputControlPositions(commonGeom, excludedCtrls, buscorr);
                
            case 'Logging & Autoscaling'
                [sheetDims,ctrlPos] = ...
                    FcnLoggingCtrlPosition(commonGeom,sheetDims, buscorr);
                
            case 'RTOS'
                % additional input neccessary for difference between inport and outport
                excludedCtrls = varargin{6};
                sheetDims(1) = sheetDims(1) - buscorr;
                [sheetDims, ctrlPos] = TLManageMessageCtrls('ctrlpos', commonGeom, sheetDims, excludedCtrls);
                % move groupbox panel before calculate tree control positions
                ctrlPos.messageGroupbox(1) = ctrlPos.messageGroupbox(1) + buscorr;
                [sheetDims, ctrlPos] = FcnTreeviewCtrlPosition(commonGeom, sheetDims, ctrlPos);
                
            case 'AUTOSAR'
                % additional input 'excludedCtrls' neccessary for bus ports
                sheetDims(1) = sheetDims(1) - buscorr;
                [sheetDims, ctrlPos] = TLManageAutosarCtrls('ctrlpos', commonGeom, sheetDims);
                % move groupbox panel before calculate tree control positions
                ctrlPos.scInfoGroupbox(1) = ctrlPos.scInfoGroupbox(1) + buscorr;
                ctrlPos.AutosarGroupbox(1) = ctrlPos.AutosarGroupbox(1) + buscorr;
                ctrlPos.dualEditText(1) = ctrlPos.dualEditText(1) + buscorr;
                [sheetDims, ctrlPos] = FcnTreeviewCtrlPosition(commonGeom, sheetDims, ctrlPos);
                
            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 0;
                [sheetDims,ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos',commonGeom,sheetDims,bCodeComment,bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;
        
    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = find(strcmp(pageName, dlgdata.pageNames));
        % create a hyperlink to transform the block to a normal port
        if ~isfield(dlgdata.SystemButtons, 'TransformLink') && ~dlgdata.bLocked
            dlgdata = FcnCreateTransformLink(dlgfig, dlgdata);
        end
        switch pageName
            case 'Output'
                dlgdata = FcnCreateOutputPage(pageNum, dlgfig, dlgdata);
                
            case 'Logging & Autoscaling'
                dlgdata = FcnCreateLoggingPage(pageNum, dlgfig, dlgdata);
                
            case 'RTOS'
                dlgdata = FcnCreateRtosPage(pageNum, dlgfig, dlgdata);
                
            case 'AUTOSAR'
                dlgdata = FcnCreateAutosarPage(pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create',pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;
        
    case 'Manage'
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = find(strcmp(pageName, dlgdata.pageNames));
        switch pageName
            case 'Output'
                [dlgdata,bModified] = ...
                    FcnManageOutputPage(dlgfig,dlgdata,pageAction);
                
            case 'Logging & Autoscaling'
                [dlgdata,bModified] = ...
                    FcnManageLoggingPage(pageNum,dlgdata,pageAction);
                
            case 'RTOS'
                [dlgdata,bModified] = ...
                    FcnManageRtosPage(pageNum,dlgdata,pageAction);
                
            case 'AUTOSAR'
                bIsOutport = varargin{5};
                [dlgdata,bModified] = ...
                    FcnManageAutosarPage(pageNum,dlgdata,pageAction,bIsOutport);
                
            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback',pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};
        
        switch pageNum
            case 1
                % Output page
                % update all controls
                dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum);
                
            case 2
                % Logging page
                dlgdata = FcnUpdateLoggingPage(dlgfig, dlgdata, pageNum);
                
            case 3
                % RTOS
                bIsOutport = varargin{4};
                dlgdata = FcnUpdateRtosPage(dlgfig, dlgdata, pageNum, bIsOutport);
                
            case 4
                % AUTOSAR
                bIsOutport = varargin{4};
                excludedKinds = {'InterRunnable', 'OperationReturnValue', 'Mode-Switch'};
                dlgdata = FcnUpdateAutosarPage(dlgfig, dlgdata, pageNum, bIsOutport, excludedKinds);
                
            case 5
                % Documentation page
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        if ~dlgdata.bLocked
            % set windowButtonMotionFcn if hyperlink exists
            set(dlgfig, 'WindowButtonMotionFcn', {@FcnWindowButtonMotion, dlgdata.SystemButtons.TransformLink});
        end
        varargout = {dlgdata};
        
    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;
        
    otherwise
        if bRestoreWarnings
            tl_handle_warning_state('pop');
        end
        error(['Invalid action ''' action'''']);
end

if bRestoreWarnings
    tl_handle_warning_state('pop');
end

end

%-----------------------------------------------------------------------------------------
% FcnCreateTransformLink creates a hyperlink that trnasforms the block into normal port
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateTransformLink(dlgfig, dlgdata)

str = 'Click here to transform block into normal port block';
pos = get(dlgdata.SystemButtons.DateLabel, 'Position');
strings_and_styles = {['   ', str, '   '],   'text'};
transformLinkSize = ds_get_uicontrol_sizes(dlgdata.commonGeom, strings_and_styles);
transformLinkPos = [dlgdata.commonGeom.frameSideEdgeBuffer, pos(2), transformLinkSize];
dlgdata.SystemButtons.TransformLink = uicontrol( ...
    'Parent',             dlgfig, ...
    'Style',              'text', ...
    'ForegroundColor',    'blue', ...
    'FontAngle',          'italic', ...
    'Enable',             'inactive', ...
    'String',             str, ...
    'Position',           transformLinkPos, ...
    'ButtonDownFcn',      @FcnTransformPort);
end


%-----------------------------------------------------------------------------------------
% FcnWindowButtonMotion manages the variable control callbacks
%
% INPUT ARGUMENTS
%   hObject         handle to figure1 (see GCBO)
%   eventdata       reserved - to be defined in a future version of MATLAB
%   hTransformLink  handle of link control
%
% OUTPUT ARGUMENTS
%   - / -
%-----------------------------------------------------------------------------------------
function FcnWindowButtonMotion(hObject, eventdata, hTransformLink)      %#ok<INUSL>

if ~isempty(hTransformLink)
    cp = get(hObject, 'currentpoint');
    pos = get(hTransformLink, 'position');
    bIsOverPosition = inpolygon(cp(1), cp(2), [pos(1) pos(1) pos(1)+pos(3) pos(1)+pos(3)], ...
        [pos(2) pos(2)+pos(4) pos(2)+pos(4) pos(2)]);
    if bIsOverPosition
        % set pointer to 'hand'
        set(hObject, 'Pointer', 'hand')
    else
        % reset pointer
        set(hObject, 'Pointer', 'arrow')
    end
end
end


%-----------------------------------------------------------------------------------------
% FcnTransformPort creates a hyperlink that transforms the block into normal port
%
% INPUT ARGUMENTS
%   src         source of button down callback
%   event       event which triggered the callback
%
% OUTPUT ARGUMENTS
%   -/-
%-----------------------------------------------------------------------------------------
function FcnTransformPort(src, event) %#ok<INUSD>

msg = ['Note that all TargetLink settings will be lost by transforming the ', ...
    'busport block into a normal port block. Continue anyway?'];
% make sure, that question is invoked
savedBatchMode = ds_error_get('batchmode');
ds_error_set('batchmode', 'off');
[btn, h] = ds_msgbox( ...
    'Message',      msg, ...
    'Style',        'question', ...
    'Button',       {'OK','Cancel'}, ...
    'Default',      'OK', ...
    'Close',        'manual');
ds_error_set('batchmode', savedBatchMode);
while true
    if ~ishandle(h)
        return
    elseif strcmp(btn, 'Cancel')
        delete(h);
        return
    elseif strcmp(btn, 'OK')
        delete(h);
        break
    end
end

% get dialog data struct
dlgfig = get(src, 'Parent');
dlgdata = get(dlgfig, 'UserData');

% substitute masktype and reset blockdata
blockType = get_param(dlgdata.model, 'BlockType');
newMaskType = ['TL_', blockType];
set_param(dlgdata.model, 'MaskType', newMaskType);
set_param(dlgdata.model, 'data', '{''date'', 730486}');

% close old dialog window and open block dialog for new blocktype
delete(dlgfig);
open_system(dlgdata.model);
end

%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end
        
    case 'ViewCode'
        if isempty(dlgdata.currentNode)
            tl_create_links_to_model('ShowComputation',dlgdata.model, 'output', dlgdata.currentSignal);
        else
            tl_create_links_to_model('ShowDeclaration',dlgdata.model, 'structvar', dlgdata.currentNode);
        end
        
    case 'DualEdit'
        dlgdata.extdata.bIsEditMode = strcmp(get(dlgdata.SystemButtons.DualEdit, 'State'), 'on');
        bModified = true;
        
    otherwise
        error('Invalid callback');
        
end % switch(action)
end


%-----------------------------------------------------------------------------------------
% FcnCalcOutputControlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometry information
%   excludedCtrls   standard controls which must be invisible
%   buscorr         buffer for bustree infront of codegeneration groupbox
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcOutputControlPositions(commonGeom, excludedCtrls, buscorr)

% additional input neccessary for difference between inport and outport
[sheetDims, ctrlPos] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

% move groupbox panel before calculate tree control positions
ctrlPos.tlcgoptGroupbox(1) = ctrlPos.tlcgoptGroupbox(1) + buscorr;

% message of dual edit mode
textWidth = ctrlPos.tlcgoptGroupbox(3);
textHeight = commonGeom.textHeight;

cx = ctrlPos.tlcgoptGroupbox(1);
cy = ctrlPos.tlcgoptGroupbox(2) + ctrlPos.tlcgoptGroupbox(4) ...
    + commonGeom.editHeight / 2;

% dualEditText frame
ctrlPos.dualEditText = [cx ,cy, textWidth, textHeight];
sheetDims(2) = sheetDims(2) ...
    + textHeight;

[sheetDims, ctrlPos] = FcnTreeviewCtrlPosition(commonGeom, sheetDims, ctrlPos);
end


%-----------------------------------------------------------------------------------------
% FcnCreateOutputPage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputPage(pageNum,dlgfig,dlgdata)

% create all controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata, 'output', 1);

% prepare some data
ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;
pageName = dlgdata.pageNames{pageNum};
[dlgdata, Children]   = FcnCreateBusGroupbox(dlgdata, dlgfig, Children, ctrlPos, pageNum);

% create dualEditText
Children.dualEditText = uicontrol( ...
    'Parent',             dlgfig, ...
    'Style',              'text', ...
    'String',             ' ', ...
    'Position',           ctrlPos.dualEditText, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''dualEditText'')',pageName));

% rewrite children data
dlgdata.pageData{pageNum}.children = Children;
end

%-----------------------------------------------------------------------------------------
% FcnManageOutputPage manage control actions of output page
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageOutputPage(dlgfig,dlgdata,pageAction)

% prepare needed data
pageNum   = 1;
Children  = dlgdata.pageData{pageNum}.children;
bIsLeaf   = isempty(dlgdata.currentNode);
if bIsLeaf
    blockVar = 'output';
else
    blockVar = 'structvar';
end

% branch depending on action
switch pageAction
    case 'busTree'
        dlgdata = FcnManageTreeview(dlgdata, Children);
        bModified = 1;
        
    case 'createStructCheckbox'
        bCreateStruct = get(Children.createStructCheckbox, 'Value');
        dlgdata.data.structvar(dlgdata.currentNode).createstruct = bCreateStruct;
        bModified = 1;
        
    case 'rescanHierarchy'
        [dlgdata, bModified] = FcnRescanBusHierarchy(dlgdata);
        
    otherwise
        [dlgdata, bModified2] = TLManageVariableCtrls( ...
            'manage', pageNum, dlgfig, dlgdata, pageAction, blockVar);
        [dlgdata, bModified3] = TLManageScalingCtrls( ...
            'manage', pageNum, dlgfig, dlgdata, pageAction, blockVar);
        bModified = bModified2 | bModified3;
end
end

%--------------------------------------------------------------------------
% FcnUpdateOutputPage updates the controls of the output tab
%
% INPUT ARGUMENTS
%   dlgdata         dialog data
%   dlgfig          figure handle of dialog
%   pageNum         page Number
%
% OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum)

% early return if children are missed
Children = dlgdata.pageData{pageNum}.children;
if isempty(Children),
    return
end

if dlgdata.extdata.bIsEditMode
    msg = '   The dual edit mode is active to visualize both standard as well as AUTOSAR code generation settings. ';
    set(dlgdata.pageData{pageNum}.children.dualEditText, ...
        'String', msg, ...
        'ForegroundColor',    'w', ...
        'BackgroundColor',    [.9 .5 0], ...    % orange
        'Enable',             'on' ...
        );
else
    set(dlgdata.pageData{pageNum}.children.dualEditText, ...
        'String', ' ', ...
        'ForegroundColor',    'b', ...
        'BackgroundColor',    get(0,'DefaultUicontrolBackgroundColor'), ...
        'Enable',             'on' ...
        );
end

if dlgdata.data.autosar.useautosarcommunication && any(dlgdata.extdata.codegenmode == [0 2]) && ~dlgdata.extdata.bIsEditMode
    % AUTOSAR mode is activated, disable all output controls
    outputChildren = rmfield(Children, 'busTree');
    ctrlNames = fieldnames(outputChildren);
    ctrlNames = ctrlNames(cellfun('isempty', regexp(ctrlNames, 'Autosar', 'match')));
    userData.ctrlStatus.enable = 'off';
    structfun(@(c) (set(c,'UserData',userData)), outputChildren);
    TLSetCtrlsStatus(dlgfig, Children, ctrlNames);
else
    signalIdx   = dlgdata.currentSignal;
    nodeIdx     = dlgdata.currentNode;
    
    if ~isempty(signalIdx)
        % one of the leafs is selected
        % invoke standard update function
        dlgdata = TLManageVariableCtrls('update',pageNum,dlgdata,'output');
        dlgdata = TLManageScalingCtrls('update',pageNum,dlgdata,'output', []);
        ctrlDataCreateStructCheckbox.enable = 'off';
        FcnSaveCtrlUserData(Children, {'createStructCheckbox'}, ctrlDataCreateStructCheckbox);
    else
        dlgdata = TLManageVariableCtrls('update',pageNum,dlgdata,'structvar');
        
        % special update function if one of the nodes is selected
        ctrlDataCreateStructCheckbox.value = dlgdata.data.structvar(dlgdata.currentNode).createstruct;
        ctrlDataCreateStructCheckbox.enable = 'on';
        FcnSaveCtrlUserData(Children, {'createStructCheckbox'}, ctrlDataCreateStructCheckbox);
        
        % list of all controls
        ctrlsList = fieldnames(Children);
        ctrlsListUsed = {...
            'descEdit'...
            ctrlsList{strncmp(ctrlsList, 'class', 5)} ...
            ctrlsList{strncmp(ctrlsList, 'type', 4)} ...
            ctrlsList{strncmp(ctrlsList, 'name', 4)} ...
            };
        ctrlsListOff = setdiff(ctrlsList, ctrlsListUsed);
        ctrlsListOff(strcmp(ctrlsListOff, 'busTree')) = [];
        ctrlsListOff(strcmp(ctrlsListOff, 'createStructCheckbox')) = [];
        
        if ~dlgdata.data.structvar(nodeIdx).createstruct
            % all controls on output page must be disabled
            % Note: disabling an edit control disables also the associated label
            ctrlData.enable = 'off';
            FcnSaveCtrlUserData(Children, ctrlsListUsed, ctrlData);
        end
        
        % disable all other controls; controls of intertask communication, too.
        ctrlData.enable = 'off';
        FcnSaveCtrlUserData(Children, ctrlsListOff, ctrlData);
    end
    % set controls
    TLManageVariableCtrls('setCtrls',pageNum,dlgfig,dlgdata);
    TLManageScalingCtrls('setCtrls',pageNum,dlgfig,dlgdata);
    TLSetCtrlsStatus(dlgfig,Children, {'createStructCheckbox'});
end
end


%-----------------------------------------------------------------------------------------
% FcnTreeviewCtrlPosition calculates positions for blockspecific controls
%
% INPUT ARGUMENTS
%   commonGeom      common geometry information
%   sheetDims       dimension of sheet
%   ctrlPos         positions of controls
%
% OUTPUT ARGUMENTS
%   ctrlPos         modified positions of controls
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnTreeviewCtrlPosition(commonGeom, sheetDims, ctrlPos)

rowDelta = 5;

busGroupbox(1) = commonGeom.sheetSideEdgeBuffer + ...
    commonGeom.figSideEdgeBuffer;
busGroupbox(2) = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;

cx = commonGeom.frameSideEdgeBuffer;
cy = commonGeom.frameBottomEdgeBuffer;

% calculate rescan bus hierarchy pushbutton
ctrlPos.rescanBusPushButton = [cx, cy, commonGeom.treeviewWidth, commonGeom.sysButtonHeight];
cy = cy + commonGeom.sysButtonHeight + rowDelta;

% correct treeviewHeight if neccessary
maxFrameHeight = sheetDims(2) - commonGeom.sheetBottomEdgeBuffer - commonGeom.textHeight - rowDelta;
maxTreeHeight = maxFrameHeight - commonGeom.frameBottomEdgeBuffer - commonGeom.frameTopEdgeBuffer ...
    - commonGeom.checkboxHeight - rowDelta - commonGeom.sysButtonHeight - rowDelta;
treeviewHeight = max(commonGeom.treeviewHeight, maxTreeHeight);
ctrlPos.treeview = [cx+busGroupbox(1), cy+busGroupbox(2), commonGeom.treeviewWidth, treeviewHeight];

% calculate bus groupbox
busGroupboxWidth  = commonGeom.treeviewWidth + ...
    2 * commonGeom.frameSideEdgeBuffer;
busGroupboxHeight = treeviewHeight + ...
    commonGeom.checkboxHeight + ...
    rowDelta + ...
    commonGeom.sysButtonHeight + ...
    rowDelta + ...
    commonGeom.frameTopEdgeBuffer + ...
    commonGeom.frameBottomEdgeBuffer;

ctrlPos.busGroupbox = [busGroupbox(1:2) busGroupboxWidth busGroupboxHeight];

cy = cy + ...
    treeviewHeight + ...
    rowDelta;
ctrlPos.createStructCheckbox = [cx , cy, commonGeom.treeviewWidth, commonGeom.textHeight];

% correct the sheet dimension
sheetDims(1) = sheetDims(1) ...
    + ctrlPos.busGroupbox(3) ...
    + commonGeom.frameDelta;
sheetDims(2) = busGroupboxHeight + ...
    commonGeom.textHeight + rowDelta +...
    commonGeom.sheetBottomEdgeBuffer;
end


%-----------------------------------------------------------------------------------------
% FcnCreateBusGroupbox creates the blockspecific controls
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   Children    control handle of current page
%   ctrlPos     control positions
%   pageNum     number of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   Children    modified control handle of current page
%-----------------------------------------------------------------------------------------
function [dlgdata, Children] = FcnCreateBusGroupbox(dlgdata, dlgfig, Children, ctrlPos, pageNum)

pageName = dlgdata.pageNames{pageNum};
% correct control positions of tree control, because AUTOSAR tab determine height
if ~isempty(dlgdata.pageData{4}.ctrlPos)
    ctrlPos.treeview = dlgdata.pageData{4}.ctrlPos.treeview;
    ctrlPos.busGroupbox = dlgdata.pageData{4}.ctrlPos.busGroupbox;
    ctrlPos.createStructCheckbox = dlgdata.pageData{4}.ctrlPos.createStructCheckbox;
end

% find children
idx = find(~cellfun('isempty', { dlgdata.pageData{1}.children, ...
    dlgdata.pageData{2}.children, ...
    dlgdata.pageData{3}.children, ...
    dlgdata.pageData{4}.children ...
    }));
% remove current page index
idx(idx == pageNum) = [];

if isempty(idx)
    % create treeview frame
    Children.busGroupbox = uipanel( ...
        'Parent',            dlgfig, ...
        'Title',            {'Bus hierarchy'}, ...
        'Units',            'pixels', ...
        'Position',          ctrlPos.busGroupbox);
    bModelIsTllib = any(strcmp(get_param(bdroot(dlgdata.model), 'Name'), {'tllib', 'tl_autosar_lib'}));
    % if time stamp is equal to 2000-01-01 retrieve the bus hierarchy
    if dlgdata.data.date == 730486 && ~bModelIsTllib
        [dispSignals, bAbort] = FcnGetBusSignals(dlgdata.model);
        if bAbort
            dispSignals = dlgdata.data.signals;
        elseif isempty(dispSignals)
            msg = ['Block data initialization failed because the bus hierarchy could not be determined. ', ...
                'Check whether the port is connected to the desired bussignal or the bus is associated ', ...
                'with a Simulink.Bus object which exist in MATLAB''s base workspace!'];
            % make sure, that message is invoked
            savedBatchMode = ds_error_get('batchmode');
            ds_error_set('batchmode', 'off');
            ds_msgbox( ...
                'Message',       msg, ...
                'Title',         'Block data initialization failed', ...
                'Style',         'error');
            ds_error_set('batchmode', savedBatchMode);
            dispSignals = dlgdata.data.signals;
        else
            dlgdata.data = tl_repair_busdata(dlgdata.model, dlgdata.data, dispSignals);
        end
    else
        dispSignals = dlgdata.data.signals;
    end
    if isempty(dlgdata.data.signals{1}{1})
        % replace empty root bus name only in dialog
        dispSignals{1}{1} = '/';
    end
    % uitree needs figure handle
    hdlgfig = get(dlgfig,'Parent');
    Children.busTree = FcnCreateTreeview(hdlgfig, dispSignals, Children.busGroupbox);
    set(Children.busTree, 'Units', 'pixels');
    set(Children.busTree, 'Position', ctrlPos.treeview);
    
    % create rescan hierarchy button
    Children.rescanHierarchy = uicontrol( ...
        'Parent',       Children.busGroupbox, ...
        'String',       'Rescan bus hierarchy', ...
        'Style',        'Pushbutton', ...
        'Position',     ctrlPos.rescanBusPushButton);
    
    dlgdata.currentNode = 1;
    dlgdata.currentSignal = [];
else
    Children.busGroupbox = dlgdata.pageData{idx(1)}.children.busGroupbox;
    Children.busTree = dlgdata.pageData{idx(1)}.children.busTree;
    Children.rescanHierarchy = dlgdata.pageData{idx(1)}.children.rescanHierarchy;
    if ~isempty(dlgdata.currentNode)
        % correct value of currentSignal
        dlgdata.currentSignal = [];
    end
end

if pageNum == 1
    Children.createStructCheckbox = uicontrol( ...
        'Parent',             Children.busGroupbox, ...
        'String',             'Create bus struct', ...
        'Style',              'Checkbox', ...
        'Position',           ctrlPos.createStructCheckbox, ...
        'Callback',           sprintf('tldlg(''%s'',gcbf,''createStructCheckbox'')',pageName));
end
end


%-----------------------------------------------------------------------------------------
% FcnCreateTreeview creates the treeview
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   treecell    cell array of bus structure
%
% OUTPUT ARGUMENTS
%   hTree       handle of new treeview
%-----------------------------------------------------------------------------------------
function hTree = FcnCreateTreeview(dlgfig, treecell, hPanel)

% disable warnings for deprecated and migrating tree view functions
% suppress deprecated warnings
warning('off', 'MATLAB:uitreenode:DeprecatedFunction');
warning('off', 'MATLAB:uitreenode:MigratingFunction');
warning('off', 'MATLAB:uitree:DeprecatedFunction');
warning('off', 'MATLAB:uitree:MigratingFunction');

imagePath = tl_get_specialfolder('TLIcons');
iconPath = [imagePath '\node_16x16.png'];
root = uitreenode(ds_var2str(treecell), treecell{1}{1}, iconPath, false);
hTree = uitree(dlgfig, ...
    'Root', root, ...
    'Parent', hPanel', ...
    'ExpandFcn', @FcnExpfcn);

jtree = hTree.getTree;
set(jtree, 'MousePressedCallback', @mousePressedCallback);
set(jtree, 'KeyPressedCallback', @mousePressedCallback);

% Set the mouse-press callback
    function mousePressedCallback(tree, value)  %#ok
        
        pause(0.01);
        tldlg('tree', dlgfig, 'busTree');
    end
end


%-----------------------------------------------------------------------------------------
% FcnExpfcn help function of FcnCreateTreeview to expand tree
%
% INPUT ARGUMENTS
%   hTree       handle of treeview
%   value       current tree structure
%
% OUTPUT ARGUMENTS
%   nodes       nodes of current tree
%-----------------------------------------------------------------------------------------
function nodes = FcnExpfcn(hTree, value)    %#ok

% disable warnings for deprecated and migrating tree view functions
% suppress deprecated warnings
warning('off', 'MATLAB:uitreenode:DeprecatedFunction');
warning('off', 'MATLAB:uitreenode:MigratingFunction');

cnt = 0;
treeStruct = tl_eval_brace_string(value,1);
treeStruct = treeStruct{1}{2};

for k = 1 : size(treeStruct,1)
    cnt = cnt + 1;
    imagePath = tl_get_specialfolder('TLIcons');
    if ischar(treeStruct{k})
        iconPath = [imagePath '\leaf_16x16.png'];
        signalName = treeStruct{k};
    else
        iconPath = [imagePath '\node_16x16.png'];
        signalName = treeStruct{k}{1};
    end
    nodes(cnt) = uitreenode(ds_var2str(treeStruct(k)), ...
        signalName, iconPath, ischar(treeStruct{k})); %#ok<AGROW>
end

if (cnt == 0)
    nodes = [];
end
end


%-----------------------------------------------------------------------------------------
% FcnManageTreeview manage control actions of blockspecific controls
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   Children    control handle of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnManageTreeview(dlgdata, Children)

hTree = Children.busTree;
dispSignals = dlgdata.data.signals;
[treeStruct, dummynodes, leafs] = tl_get_treestruct(dispSignals);

nodes = hTree.SelectedNodes;
if isempty(nodes)
    return
end
node = nodes(1);
% get complete signal name
path = node.getPath;
for i=1:length(path);
    p{i} = char(path(i).getName); %#ok<AGROW>
end
if length(p) > 1
    path = fullfile(p{:});
else
    path = p{1};
end
signal = strrep(path, '\', '.');
% special case, empty root node is displayed by '/'
signal = strrep(signal, '/', '');
% find signal in tree structure; signal should be unique, because it contains whole path.
idx = find(strcmp(signal,{treeStruct.path}));
if isempty(idx)
    % select root node
    idx = 1;
end
% set current selected element in dlgdata
dlgdata.currentSignal = treeStruct(idx).leafIdx;
dlgdata.currentNode = treeStruct(idx).nodeIdx;
dlgdata.currentSignalName = treeStruct(idx).name;
if ~isempty(dlgdata.currentSignal)
    % signal name of simulated ranges is needed
    dlgdata.signalName = leafs{dlgdata.currentSignal};
end
hTree.repaint;
end


%-----------------------------------------------------------------------------------------
% FcnRescanBusHierarchy determines current bus hierarchy and updates blockdata accordingly
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   signals modified data
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnRescanBusHierarchy(dlgdata)

bModified = false;
set(dlgdata.SystemButtons.StatusLabel, 'String', 'Rescanning bus hierarchy ...')

% disable warnings for deprecated and migrating tree view functions
% suppress deprecated warnings
warning('off', 'MATLAB:uitreenode:DeprecatedFunction');
warning('off', 'MATLAB:uitreenode:MigratingFunction');

% make sure, that messages are invoked
savedBatchMode = ds_error_get('batchmode');
% ds_error_set('batchmode', 'off'); % ds_error_none sets batchmode to 'off'
ds_error_none;
[busSignals, bAbort] = FcnGetBusSignals(dlgdata.model);
if bAbort
    ds_error_set('batchmode', savedBatchMode);
    set(dlgdata.SystemButtons.StatusLabel, 'String', 'Rescanning bus hierarchy ... aborted')
    return
elseif isempty(busSignals)
    % if no messages are thrown during model compilation then report an own message
    if ~ds_error_check
        msg = 'The signal passing through this block doesn''t seem to be a bus signal!';
        ds_msgbox( ...
            'Message',      msg, ...
            'Title',        'No bussignal found', ...
            'Style',        'error');
    end
elseif ~isequal(dlgdata.data.signals, busSignals)
    % comparison of blockdata with current bus structure revealed that block
    % data are not suitable for current bus structure.
    ds_error_msg({'', ...
        'The structure of the bus signal that is passed with this block', ...
        'has been modified. The block''s data will be adjusted accordingly.' ...
        '', ...
        'To make sure that the block data match the structure of the bus,' ...
        'press Ok or Apply in the block''s dialog.', ...
        'To keep the current bus data, press Cancel.'}, ...
        'Title', 'Block data do not match bus signal', ...
        'RegisterMessage', 'off', ...
        'MessageType','note');
    % get suitable data
    dlgdata.data = tl_repair_busdata(dlgdata.model,dlgdata.data,busSignals);
    % update tree
    imagePath = tl_get_specialfolder('TLIcons');
    iconPath = [imagePath '\node_16x16.png'];
    hTree = dlgdata.pageData{dlgdata.CurrentPageNum}.children.busTree;
    if isempty(busSignals{1}{1})
        % replace empty root bus name only in dialog
        busSignals{1}{1} = '/';
    end
    hTree.setRoot(uitreenode(ds_var2str(busSignals), busSignals{1}{1}, iconPath, false));
    % tree is collapsed after substituting the tree structure
    dlgdata.currentNode = 1;
    dlgdata.currentSignal = [];
    bModified = true;
end
ds_error_set('batchmode', savedBatchMode);
set(dlgdata.SystemButtons.StatusLabel, 'String', 'Rescanning bus hierarchy ... finished')
end


%-----------------------------------------------------------------------------------------
% FcnGetBusSignals retrieves current bus hierarchy
%
% INPUT ARGUMENTS
%   hBlock      handle of port block
%
% OUTPUT ARGUMENTS
%   busSignals  cell array describing bus hierarchy
%   bAbort      flag signaling a user abort
%-----------------------------------------------------------------------------------------
function [busSignals, bAbort] = FcnGetBusSignals(hBlock)

% default return value
busSignals = {};
bAbort = false;

% prefer busobject analysis if possible
if strcmp(get_param(hBlock, 'UseBusObject'), 'on')
    varStruct = evalin('base', ['whos(''', get_param(hBlock, 'BusObject'), ''')']);
    bBusObjAvail = ~isempty(varStruct) && strcmp(varStruct.class, 'Simulink.Bus');
else
    bBusObjAvail = false;
end

% does the block reside in a library or a model?
modelName = bdroot(hBlock);
if strcmp(get_param(modelName, 'BlockDiagramType'), 'model')    
    if bBusObjAvail
        bCompile = false;
    else
        msg = ['To determine the current bus hierarchy, the model must be set ', ...
            'to compiled mode. This requires an initializable model and can take a few ', ...
            'minutes. Do you want to continue with model compilation?'];
        % make sure, that question is invoked
        savedBatchMode = ds_error_get('batchmode');
        ds_error_set('batchmode', 'off');
        [btn, h] = ds_msgbox( ...
            'Message',      msg, ...
            'Style',        'question', ...
            'Button',       {'Yes','No'}, ...
            'Default',      'Yes', ...
            'Close',        'manual');
        ds_error_set('batchmode', savedBatchMode);
        while true
            if ~ishandle(h)
                bAbort = true;
                return
            elseif strcmp(btn, 'No')
                delete(h);
                bAbort = true;
                return
            elseif strcmp(btn, 'Yes')
                delete(h);
                break
            end
        end
        bCompile = isempty(get_param(hBlock, 'CompiledPortDimensions'));
    end
else
    bCompile = false;
end

% get the bussisgnals
if bCompile
    tl_init_model(modelName, 'compile');
    if isempty(get_param(hBlock, 'CompiledPortDimensions'))
        % compilation of model was not successfull
        busSignals = {};
    else
        if tl_analyze_bussignal('IsBus', hBlock)
            busSignals = tl_analyze_bussignal('GetElementNames', hBlock);
        else
            busSignals = {};
        end
        tl_init_model(modelName, 'term');
    end
elseif bBusObjAvail
    busSignals = tl_analyze_bussignal('BusObject2ElementNames', hBlock);
end
end

%-----------------------------------------------------------------------------------------
% FcnLoggingCtrlPosition calculates positions for all controls on logging page
%
% INPUT ARGUMENTS
%   commonGeom      common geometry information
%   sheetDims       dimension of sheet
%   buscorr         buffer for bustree infront of codegeneration groupbox
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%-----------------------------------------------------------------------------------------
function [sheetDims,ctrlPos] = FcnLoggingCtrlPosition(commonGeom,sheetDims, buscorr)

% modify sheetDims, because it is used for calculation autoscaling frame
sheetDims(1) = sheetDims(1) - buscorr;
excludedCtrls = {'keepParameter'};
[sheetDims, ctrlPos] = ...
    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

% move groupbox panel before calculate tree control positions
ctrlPos.autoscaleGroupbox(1) = ctrlPos.autoscaleGroupbox(1) + buscorr;
ctrlPos.logplotGroupbox(1) = ctrlPos.logplotGroupbox(1) + buscorr;

[sheetDims, ctrlPos] = FcnTreeviewCtrlPosition(commonGeom, sheetDims, ctrlPos);
end


%-----------------------------------------------------------------------------------------
% FcnCreateLoggingPage creates the logging page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateLoggingPage(pageNum,dlgfig,dlgdata)

% invoke standard routine to create logging and autoscaling controls
dlgdata = TLManageLoggingCtrls('create', pageNum,dlgfig,dlgdata);

ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;

[dlgdata, Children] = FcnCreateBusGroupbox(dlgdata, dlgfig, Children, ctrlPos, pageNum);
% rewrite children data
dlgdata.pageData{pageNum}.children = Children;
end

%-----------------------------------------------------------------------------------------
% FcnManageLoggingPage manage control actions of logging page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageLoggingPage(pageNum,dlgdata,pageAction)

% prepare some needed data
Children = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'busTree'
        dlgdata = FcnManageTreeview(dlgdata, Children);
        if isempty(dlgdata.currentNode)
            dlgdata.pageData{2}.index = dlgdata.currentSignal;
        end
        bModified = 1;
        
    case 'rescanHierarchy'
        [dlgdata, bModified] = FcnRescanBusHierarchy(dlgdata);
        
    otherwise
        [dlgdata, bModified] = ...
            TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');
end
end

%--------------------------------------------------------------------------
% FcnUpdateLoggingPage updates the controls of the logging tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateLoggingPage(dlgfig,dlgdata,pageNum)

% early return if children are missed
Children = dlgdata.pageData{pageNum}.children;
if isempty(Children),
    return
end
hdlgfig = get(dlgfig,'Parent');
defColor  = get(hdlgfig,'Color');
signalIdx = dlgdata.currentSignal;

if ~isempty(signalIdx)
    % invoke standard update function
    dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
    TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
else
    % all controls on logging page must be disabled
    set([Children.plotEdit, Children.samplesEdit, Children.lowerheadroomEdit, Children.upperheadroomEdit], ...
        'Backgroundcolor',  defColor, ...
        'String',           '', ...
        'Enable',           'off');
    set([Children.logPopup, Children.autoscalePopup], ...
        'Backgroundcolor',  defColor, ...
        'String',           ' ', ...
        'Value',            1, ...
        'Enable',           'off');
    set([Children.scalingValidCheckbox, Children.keepOutputOffsetCheckbox, Children.keepOutputDataTypeCheckbox], ...
        'Backgroundcolor',  defColor, ...
        'Value',            0, ...
        'Enable',           'off');
    set([Children.hroomUnitButton, Children.plotLabel, Children.logLabel, ...
        Children.samplesLabel, Children.autoscaleLabel, Children.hroomHeading, ...
        Children.lowerheadroomLabel, Children.upperheadroomLabel, Children.hroomUnitLabel, ...
        Children.keepHeading], ...
        'Enable',           'off');
end
end

%-----------------------------------------------------------------------------------------
% FcnCreateRtosPage creates the RTOS page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateRtosPage(pageNum,dlgfig,dlgdata)

% invoke standard routine to create RTOS controls
dlgdata = TLManageMessageCtrls('create', pageNum,dlgfig,dlgdata);

ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;

[dlgdata, Children]   = FcnCreateBusGroupbox(dlgdata, dlgfig, Children, ctrlPos, pageNum);

% rewrite children data
dlgdata.pageData{pageNum}.children = Children;
end

%-----------------------------------------------------------------------------------------
% FcnManageRtosPage manage control actions of RTOS page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageRtosPage(pageNum,dlgdata,pageAction)

% prepare some needed data
Children = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'busTree'
        dlgdata = FcnManageTreeview(dlgdata, Children);
        if isempty(dlgdata.currentNode)
            dlgdata.pageData{3}.index = dlgdata.currentSignal;
        end
        bModified = 1;
        
    case 'rescanHierarchy'
        [dlgdata, bModified] = FcnRescanBusHierarchy(dlgdata);
        
    otherwise
        [dlgdata, bModified] = ...
            TLManageMessageCtrls('manage', pageNum, dlgdata, pageAction);
end
end

%--------------------------------------------------------------------------
% FcnUpdateRtosPage updates the controls of the RTOS tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%   bIsOutport  flag =1, if block is outport, =0 otherwise
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateRtosPage(dlgfig,dlgdata,pageNum,bIsOutport)

% early return if children are missed
Children = dlgdata.pageData{pageNum}.children;
if isempty(Children),
    return
end

% prepare some data
signalIdx = dlgdata.currentSignal;

if ~isempty(signalIdx)
    % one of the leafs is selected
    % invoke standard update function
    dlgdata = TLManageMessageCtrls('update',pageNum,dlgdata);
else
    % disable all controls of intertask communication
    ctrlsListOff = {...
        'messageNamePopup' ...
        'componentPopup' ...
        'manageMessagePushButton'};
    if ~bIsOutport
        ctrlsListOff = [ctrlsListOff ...
            {'accessorPopup'}];
    end
    ctrlData.enable = 'off';
    FcnSaveCtrlUserData(Children, ctrlsListOff, ctrlData);
end
TLManageMessageCtrls('setCtrls',pageNum,dlgfig,dlgdata);
end

%-----------------------------------------------------------------------------------------
% FcnCreateAutosarPage creates the AUTOSAR page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateAutosarPage(pageNum,dlgfig,dlgdata)

% invoke standard routine to create AUTOSAR controls
dlgdata = TLManageAutosarCtrls('create', pageNum,dlgfig,dlgdata);

ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;

[dlgdata, Children]   = FcnCreateBusGroupbox(dlgdata, dlgfig, Children, ctrlPos, pageNum);

% rewrite children data
dlgdata.pageData{pageNum}.children = Children;
end

%-----------------------------------------------------------------------------------------
% FcnManageAutosarPage manage control actions of AUTOSAR page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%   bIsOutport  flag =1, if block is outport, =0 otherwise
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageAutosarPage(pageNum,dlgdata,pageAction,bIsOutport)

% prepare some needed data
Children = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'busTree'
        dlgdata = FcnManageTreeview(dlgdata, Children);
        if isempty(dlgdata.currentNode)
            dlgdata.pageData{4}.index = dlgdata.currentSignal;
        end
        bModified = 1;
        
    case 'rescanHierarchy'
        [dlgdata, bModified] = FcnRescanBusHierarchy(dlgdata);
        
    otherwise
        [dlgdata, bModified] = ...
            TLManageAutosarCtrls('manage', pageNum, dlgdata, pageAction, bIsOutport);
end
end

%--------------------------------------------------------------------------
% FcnUpdateAutosarPage updates the controls of the AUTOSAR tab
%
% INPUT ARGUMENTS
%   dlgdata         dialog data
%   dlgfig          figure handle of dialog
%   pageNum         page Number
%   bIsOutport      flag =1, if block is outport, =0 otherwise
%   excludedKinds   list of communication kinds excluded from dialog 
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateAutosarPage(dlgfig,dlgdata,pageNum,bIsOutport,excludedKinds)

% early return if children are missed
Children = dlgdata.pageData{pageNum}.children;
if isempty(Children),
    return
end

dlgdata = TLManageAutosarCtrls('update',pageNum, dlgfig, dlgdata, bIsOutport, excludedKinds);
TLManageAutosarCtrls('setCtrls',pageNum, dlgfig, dlgdata);
end

%-----------------------------------------------------------------------------------------
% FcnSaveCtrlUserData saves UserData at controls
%
% INPUT ARGUMENTS
%   Children     Structure with controls
%   ctrl         Control for which the status is set
%   ctrlStatus   Status of this control
%-----------------------------------------------------------------------------------------
function FcnSaveCtrlUserData(ctrlsStruct, ctrlsList, ctrlData)                  %#ok

% set status to control
for ctrlsNo = 1 : length(ctrlsList)
    hCtrl = eval(['ctrlsStruct.', ctrlsList{ctrlsNo}]);
    UserData = get(hCtrl, 'UserData');
    fieldNames = fields(ctrlData);
    for fieldNo = 1 : length(fieldNames)
        switch fieldNames{fieldNo}
            case 'enable'
                UserData.ctrlStatus.enable = ctrlData.enable;
            case 'iserror'
                UserData.ctrlStatus.iserror = ctrlData.iserror;
            case 'string'
                UserData.ctrlStatus.string = ctrlData.string;
            case 'value'
                UserData.ctrlStatus.value = ctrlData.value;
        end
    end
    set(hCtrl, 'UserData', UserData);
end
end
